﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.IO;
using System.Net;
using FeaturesBlog.Models;
using System.Configuration;
using System.Threading;
using System.Text.RegularExpressions;

namespace FeaturesBlog.Helpers
{
    public class MailHelper
    {
        private const string path = @"~/Content/Templates/{0}";

        private const string SendConfirmNotificationSubject = @"Подтверждение подписки";
        private const string SendCommentNotificationSubject = @"New Comment!";
        private const string SendNewPostNotificationSubject = @"New Post!";

        private enum mailType
        {
            Comment = 0,
            Post = 1,
            Confrim = 2
        };

        SmtpClient _smtp = new SmtpClient();

        private string LoadTemplate(mailType type)
        {
            string template = string.Empty;
            switch (type)
            {
                case mailType.Comment:
                    {
                        try
                        {
                            template = HttpContext.Current.Server.MapPath(string.Format(path, "NewComment.html"));
                            return File.ReadAllText(template);
                        }
                        catch (FileNotFoundException)
                        {
                            return string.Empty;
                        }
                    }
                case mailType.Post:
                    {
                        try
                        {
                            template = HttpContext.Current.Server.MapPath(string.Format(path, "NewPost.html"));
                            return File.ReadAllText(template);
                        }
                        catch (FileNotFoundException)
                        {
                            return string.Empty;
                        }
                    }
                case mailType.Confrim:
                    {
                        try
                        {
                            template = HttpContext.Current.Server.MapPath(string.Format(path, "Confirm.html"));
                            return File.ReadAllText(template);
                        }
                        catch (FileNotFoundException)
                        {
                            return string.Empty;
                        }
                    }
                default:
                    return string.Empty;
            }
        }

        public bool SendCommentNotification(Comment c)
        {
            MailMessage m = new MailMessage(ConfigurationManager.AppSettings["BlogMail"].ToString(), ConfigurationManager.AppSettings["AdminMail"].ToString());
            m.Subject = SendCommentNotificationSubject;
            string body = LoadTemplate(mailType.Comment);
            body = body.Replace(@"%Body%", c.CommentBody).Replace(@"%Date%", c.CommentDate.ToString()).Replace(@"%UserName%", c.UserDisplayName).Replace(@"%IP%", c.IP);
            m.Body = body;
            m.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            try
            {
                smtp.SendAsync(m, c.CommentId);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public bool SendConfirmNotification(UserEmail email)
        {
            MailMessage m = new MailMessage(ConfigurationManager.AppSettings["BlogMail"].ToString(), email.Email);
            m.Subject = SendConfirmNotificationSubject;

            string body = LoadTemplate(mailType.Confrim);

            string id = SecurityHelper.IntEncode((int)email.Id);

            body = body.Replace(@"%Id%", id);
            m.Body = body;
            m.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            try
            {
                smtp.SendAsync(m, email);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        private void SendAsyncNewPostNotification(IEnumerable<UserEmail> emails, string body)
        {
            SmtpClient smtp = new SmtpClient();
            MailMessage m;
            foreach (UserEmail e in emails)
            {
                m = new MailMessage(ConfigurationManager.AppSettings["BlogMail"].ToString(), e.Email);
                m.Body = body;
                m.Subject = SendNewPostNotificationSubject;
                m.IsBodyHtml = true;

                try
                {
                    smtp.Send(m);
                }
                catch (Exception)
                {
                    
                }
            }
        }

        public void SendNewPostNotification(Post p, IEnumerable<UserEmail> emails)
        {
            string body = LoadTemplate(mailType.Post);
            PostModel pm = new HtmlHelpers().EncodeHtmlForPost(new PostModel() { BlogPost = p });
            body = body.Replace(@"%PostSubject%", p.PostSubject).Replace(@"%PostDate%", p.PostDate.ToShortDateString()).Replace(@"%PostBody%", pm.BlogPost.PostBody);
           
            ThreadStart ts = delegate() { SendAsyncNewPostNotification(emails, body); };
            Thread newThread = new Thread(ts);
            newThread.Start();
        }

        public static bool ValidateEmail(string email)
        {
            Regex regex = new Regex(@"^[-a-z0-9!#$%&'*+/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*@([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\.)*(aero|arpa|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|[a-z][a-z])$");
            bool m = regex.IsMatch(email);
            return m;
        }
    }
}